# coding: utf-8


''' 
rabbitMq 消息测试

'''

import pika # 1.1.0
import json

# UAT
Host = '172.18.100.74'

Port = 5672
User = 'guest'
Passwd = 'guest'


class MQ_Handler():
    
    def __init__(self, host=Host, port=Port, usr=User, pwd=Passwd):
        crd = pika.PlainCredentials(usr, pwd)
        # 虚拟队列需要指定参数 virtual_host，如果是默认的可以不填。
        self.conn = pika.BlockingConnection(pika.ConnectionParameters(
                                                host=Host, 
                                                port=Port, 
                                                virtual_host='/', 
                                                credentials=crd)
                                            )
        self.channel = self.conn.channel()
    
    def _set_queue(self, q_name):
        # 声明消息队列，消息将在这个队列传递，如不存在，则创建
        self.channel.queue_declare(queue=q_name)

    def _callback(self, ch, method, properties, body):
        print "msg_bod: %s" % body
        self.channel.basic_ack(delivery_tag=method.delivery_tag)
        return body

    def bind_exchange(self, ex_name, q_name):
        self.channel.queue_bind(exchange=ex_name, queue=q_name)

    def get_msg(self, q_name):
        # self._set_queue(q_name)
        # 调用回调函数，从队列里取消息
        self.channel.basic_consume(q_name, self._callback)
        self.channel.start_consuming()
        print "done"

    def del_queue(self, q_name):
        self.channel.queue_delete(queue=q_name)


if __name__ == '__main__':
    mq = MQ_Handler()
    # q_name = 'audioPlatform_queue_recv_ali_G2_2_0_release_SH_172_18_10_100'
    ex_name = 'opens.nlu.terminfo.v2' # 发布词典
    q_name = 'dakang_uat_debug'
    # mq.bind_exchange(ex_name, q_name)
    mq.get_msg(q_name)